/* eslint-disable array-bracket-spacing */
/* eslint-disable no-dupe-class-members */
/* eslint-disable indent */
'use strict'

const Service = require('egg').Service
const dayjs = require('dayjs')

// 信息要返回的字段
const attributes = ['id', 'mid', 'openid', 'unionid', 'phone', 'nickname', 'avatar', 'sex', 'birthday', 'register_time', 'last_login_time', 'level_name', 'subscribe', 'subscribe_time', 'pid', 'card_id', 'balance', 'status']
const place_attributes = ['barname', 'barcode']

class MemberService extends Service {

    // 查询所有列表
    async getMemberList(params) {
        const { model, helper } = this.ctx
        const currentPage = params?.pageIndex ?? 1
        const pageSize = params?.pageSize ?? 50
        const { Op } = require('sequelize')
        const where = {}
        if (params.key) {
            where.nickname = {
                [Op.like]: `%${params.key}%`
            }
            where.phone = {
                [Op.like]: `%${params.key}%`
            }
        }
        if (params.start_time && params.end_time) {
            where.register_time = {
                [Op.between]: [params.start_time, params.end_time]
            }
        }
        if (params.status !== undefined && params.status != null) {
            where.status = params.status
        }
        if (params.pid !== undefined && params.pid != null) {
            where.pid = params.pid
        }

        return await model.Member.findAndCountAll({
            where,
            offset: (currentPage - 1) * pageSize, // 计算分页偏移量
            limit: pageSize,
            attributes,
            include: [
                {
                    model: model.Place,
                    // as: 'place',
                    attributes: place_attributes
                }
            ],
            order: [
                ['level_name', 'ASC'],
                ['register_time', 'DESC']
            ]
        })
            .then(async result => {
                if (result) {
                    return {
                        list: result.rows,
                        total: result.count
                    }
                }
                helper.failed(1008, null, '查询会员列表失败')
                return false
            })
            .catch(async error => {
                helper.failed(1001, null, error.errors[0]?.message)
                return false
            })
    }

    // 新增
    async createMember(params) {
        const { model, helper, logger } = this.ctx

        return await model.Member.create({
            ...params,
            register_time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
            created_at: dayjs().format('YYYY-MM-DD HH:mm:ss'),
            updated_at: dayjs().format('YYYY-MM-DD HH:mm:ss')
        })
            .then(async data => {
                if (data) {
                    return data
                }
                helper.failed(1005, null, '新增会员信息失败')
                return false
            })
            .catch(async error => {
                if (error?.original?.sqlMessage) {
                    logger.error(`新增会员失败   pid:[${params.pid}]  mid:[${params.mid}]  ${error?.original?.sqlMessage}`)
                    helper.failed(1001, null, error?.original?.sqlMessage)
                } else if (error?.errors[0]?.message) {
                    logger.error(`新增会员失败   pid:[${params.pid}] mid:[${params.mid}]  ${error.errors[0]?.message}`)
                    helper.failed(1001, null, error.errors[0]?.message)
                } else {
                    logger.error(`新增会员失败   pid:[${params.pid}] mid:[${params.mid}]  ${JSON.stringify(error)}`)
                    helper.failed(1001, null, JSON.stringify(error))
                }
                return false
            })
    }

    // 编辑
    async editMember(params) {
        const { model, helper, logger } = this.ctx

        return await model.Member.findByPk(params.id)
            .then(async result => {
                if (result) {
                    delete params.id
                    return await result.update(params)
                        .then(async data => {
                            if (data) {
                                return data
                            }
                            helper.failed(1006, null, '编辑会员信息失败')
                            return false
                        })
                        .catch(async error => {
                            if (error?.original?.sqlMessage) {
                                logger.error(`修改会员失败   id:[${params.id}]  ${error?.original?.sqlMessage}`)
                                helper.failed(1001, null, error?.original?.sqlMessage)
                            } else if (error?.errors[0]?.message) {
                                logger.error(`修改会员失败   id:[${params.id}]  ${error.errors[0]?.message}`)
                                helper.failed(1001, null, error.errors[0]?.message)
                            } else {
                                logger.error(`修改会员失败   id:[${params.id}]  ${JSON.stringify(error)}`)
                                helper.failed(1001, null, JSON.stringify(error))
                            }
                            return false
                        })
                }
                helper.failed(1004, null, '会员信息不存在')
                return false
            })
            .catch(async error => {
                if (error?.original?.sqlMessage) {
                    logger.error(`修改会员失败   id:[${params.id}]  ${error?.original?.sqlMessage}`)
                    helper.failed(1001, null, error?.original?.sqlMessage)
                } else if (error?.errors[0]?.message) {
                    logger.error(`修改会员失败   id:[${params.id}]  ${error.errors[0]?.message}`)
                    helper.failed(1001, null, error.errors[0]?.message)
                } else {
                    logger.error(`修改会员失败   id:[${params.id}]  ${JSON.stringify(error)}`)
                    helper.failed(1001, null, JSON.stringify(error))
                }
                return false
            })
    }

    // 创建OR更新
    async create_update_Member(params) {
        const { model, helper, logger } = this.ctx

        const where = {
            mid: params.mid,
            pid: params.pid
        }

        const [member, isCreated] = await model.Member.findOrCreate({
            where,
            defaults: {
                ...params,
                register_time: dayjs().format('YYYY-MM-DD HH:mm:ss')
            } // 如果没有找到，将使用这些信息来创建
        })

        if (isCreated) {
            return member
        }
        return await member.update(params)
            .then(async data => {
                if (data) {
                    return data
                }
                helper.failed(1006, null, '编辑会员信息失败')
                return false
            })
            .catch(async error => {
                if (error?.original?.sqlMessage) {
                    logger.error(`编辑会员失败   pid:[${params.pid}]  mid:[${params.mid}]  ${error?.original?.sqlMessage}`)
                    helper.failed(1001, null, error?.original?.sqlMessage)
                } else if (error?.errors[0]?.message) {
                    logger.error(`编辑会员失败   pid:[${params.pid}] mid:[${params.mid}]  ${error.errors[0]?.message}`)
                    helper.failed(1001, null, error.errors[0]?.message)
                } else {
                    logger.error(`编辑会员失败   pid:[${params.pid}] mid:[${params.mid}]  ${JSON.stringify(error)}`)
                    helper.failed(1001, null, JSON.stringify(error))
                }
                return false
            })
    }

    // 删除
    async deleteMember(params) {
        const { model, helper, logger } = this.ctx

        return await model.Member.findByPk(params.id)
            .then(async result => {
                if (result) {
                    return await result.destroy()
                        .then(async data => {
                            if (data) {
                                return data
                            }
                            helper.failed(1007, null, '删除会员失败')
                            return false
                        })
                        .catch(async error => {
                            if (error?.original?.sqlMessage) {
                                logger.error(`删除会员失败   id:[${params.id}] ${error?.original?.sqlMessage}`)
                                helper.failed(1001, null, error?.original?.sqlMessage)
                            } else if (error?.errors[0]?.message) {
                                logger.error(`删除会员失败   id:[${params.id}] ${error.errors[0]?.message}`)
                                helper.failed(1001, null, error.errors[0]?.message)
                            } else {
                                logger.error(`删除会员失败   id:[${params.id}] ${JSON.stringify(error)}`)
                                helper.failed(1001, null, JSON.stringify(error))
                            }
                            return false
                        })
                }
                helper.failed(1004, null, '会员信息不存在')
                return false
            })
            .catch(async error => {
                if (error?.original?.sqlMessage) {
                    logger.error(`删除会员失败   id:[${params.id}] ${error?.original?.sqlMessage}`)
                    helper.failed(1001, null, error?.original?.sqlMessage)
                } else if (error?.errors[0]?.message) {
                    logger.error(`删除会员失败   id:[${params.id}] ${error.errors[0]?.message}`)
                    helper.failed(1001, null, error.errors[0]?.message)
                } else {
                    logger.error(`删除会员失败   id:[${params.id}] ${JSON.stringify(error)}`)
                    helper.failed(1001, null, JSON.stringify(error))
                }
                return false
            })
    }


}

module.exports = MemberService
